import React, { useEffect, useRef, useState } from 'react'
import Child from './Child'

export default function App() {
  /* 
  定义状态: 
      const [xxx, setXxx] = useState(initValue)
      一旦调用函数setXxx: 将新的Value去更新内部状态数据 => 重新渲染组件(重新调用组件函数)
      调用setXxx的2种方式:
        setXxx(newVal)
        setXxx(val => newVal)
  */
  const [msg, setMsg] = useState('abc')
  const [count, setCount] = useState(1)

  /* 
  useEffect: 模拟类组件的生命周期
    1. didMount    useEffect(() => {}, [])
    2. didMount + didUpdate    useEffect(() => {})
    3. didMount + 某个数据更新的didUpdate   useEffect(() => {}, [count])
  */

  useEffect(() => {
    setTimeout(() => {
      // setCount(count + 3)
      setCount(val => val + 3)  // 根据内部最新的值增加
    }, 2000);
  }, [])

  useEffect(() => {
    setTimeout(() => {
      setMsg(val => val.split('').reverse().join(''))
    }, 3000);
  }, [])

  /* 
  useRef: 存储标签对象和其它自定义数据
  */
  const inputRef = useRef()

  // inputRef.current

  return (
    <>
      <p>msg: {msg}</p>
      <p>count: {count}</p>
      <button onClick={() => setCount(count + 1)}>增加</button>
      <div>
        <input type="text" ref={inputRef}/>
        <button onClick={() => alert(inputRef.current.value)}>提示输入</button>
      </div>
      <hr/>

      <Child count={count} setCount={setCount}/>
    </>
  )
}
